package com.beerandjesus.sportofkings.handicapper.strategy;

import com.beerandjesus.sportofkings.handicapper.model.JockeyAtDistanceOrOnTurf;
import com.beerandjesus.sportofkings.handicapper.model.TrainerJockeyOwner;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.MathContext;

/**
 * Calculate a jockey win percentage, using statistics in the following order:
 * Current meet statistics if there are 10 starts or more, otherwise career
 * statistics at distance or on turf if there are 10 starts or more, otherwise
 * return null.
 * Date: Sep 27, 2012
 * Time: 7:31:19 PM
 */
@Component
public class JockeyPerformanceResolverImpl implements JockeyPerformanceResolver {
    private static final Logger LOG = Logger.getLogger(JockeyPerformanceResolverImpl.class);

    public BigDecimal getWinPercentage(TrainerJockeyOwner tjo, JockeyAtDistanceOrOnTurf jock) {
        if (tjo == null && jock == null) {
            return null;
        }
        if (tjo != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Rating " + tjo.getJockeyName() + " by current meet stats");
            }
            try {
                return getPercentage(tjo.getJockeyCurrentMeetStarts(), tjo.getJockeyCurrentMeetWins());
            } catch (EarlyInTheMeetException e) {
                // Okay
            }
        }
        if (jock == null) {
            return null;
        }
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Rating jockey by at distance/on turf stats");
            }
            return getPercentage(jock.getStarts(), jock.getWins());
        } catch (EarlyInTheMeetException e) {
            return null;
        }
    }

    private BigDecimal getPercentage(String s, String w) throws EarlyInTheMeetException {
        BigDecimal starts = null;
        try {
            starts = new BigDecimal(s);
        } catch (Exception e) {
            // Ignore
        }
        if (starts == null || starts.compareTo(new BigDecimal(10)) < 0) {
            throw new EarlyInTheMeetException();
        }
        BigDecimal wins = null;
        try {
            wins = new BigDecimal(w);
        } catch (Exception e) {
            // Ignore
        }
        if (wins != null) {
            BigDecimal winPercentage = wins.divide(starts, MathContext.DECIMAL32);
            if (LOG.isDebugEnabled()) {
                LOG.debug(wins + " / " + starts + " = " + winPercentage);
            }
            return winPercentage;
        }
        return null;

    }
}
